import time,json
from coolApkAPI import coolApkAPI
from typing import List, Optional
import random



# 全局变量记录已使用的回复和最后使用时间
used_replies = []
last_reset_time = time.time()

def load_replies(file_path: str = 'replyText.json') -> List[str]:
    """加载回复文本列表"""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            return json.load(f)["universal_replies"]
    except (FileNotFoundError, json.JSONDecodeError, KeyError) as e:
        print(f"加载回复文件失败: {str(e)}")
        return []


def get_random_reply(reply_list: List[str]) -> Optional[str]:
    """
    获取随机回复，确保10分钟内不重复
    """
    global used_replies, last_reset_time

    # 检查是否需要重置已用列表（超过10分钟）
    current_time = time.time()
    if current_time - last_reset_time > 600:  # 10分钟=600秒
        used_replies = []
        last_reset_time = current_time

    # 过滤掉已使用的回复
    available_replies = [reply for reply in reply_list if reply not in used_replies]

    if not available_replies:
        # 如果没有可用回复，重置已用列表
        used_replies = []
        available_replies = reply_list.copy()
        print("所有回复已使用一遍，已重置选择池")

    # 随机选择一个回复
    selected = random.choice(available_replies)
    used_replies.append(selected)

    return selected

if __name__ == '__main__':
    reply_texts = load_replies()
    ## ==== 读取存储的 headers
    with open('headers.json', 'r', encoding='utf-8') as f:
        headers = json.loads(f.read())

    ## ==== 初始化接口
    api = coolApkAPI(headers)

    ## 获取最新话题
    datalist = api.dataList()

    for data in datalist["data"]:
        # 只获取用户的帖子
        id = data.get("id")
        if id and id != "" and id != None:
            title = data.get("message").split("</a>")[1].replace("\n", "")
            print(f"编号{data.get('id')}:{title}")
            id = str(id)
            # 点赞
            api.posts_like(id)
            replyText = get_random_reply(reply_texts)
            # 回复
            api.posts_reply(id, replyText)
            time.sleep(30)